package com.aaa.affair.service.impl;

import com.aaa.affair.dao.BookShopDao;
import com.aaa.affair.service.BookShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: whj
 * @Version 1.0
 * @Date: 2022/11/14  16:59
 */
@Service
public class BookShopServiceImpl implements BookShopService {
    @Autowired
    private BookShopDao bookShopDao;

    //线程并发问题: 库存超卖。---业务层 业务逻辑比较复杂时，需要调用多个dao层代码
    @Override
   @Transactional
//    //批量购买
//    @Transactional(propagation = Propagation.REQUIRED)
    public void purchase(String isbn, String username) {
        //1. 根据图书编号查询图书对应的价格
        int price = bookShopDao.findBookPriceByIsbn(isbn);

        //判断库存是否够
        int stock = bookShopDao.findStockByIsbn(isbn);
        if(stock>0) {
            //2. 修改库存
            bookShopDao.updateBookStock(isbn);
        }else{
            throw new RuntimeException("图书编号:"+isbn+"-->库存不足");
        }
        //判断余额是否够
        int balance = bookShopDao.findBalanceByUsername(username);
        if(balance>=price) {
            //3. 修改账户余额
            bookShopDao.updateAccount(username, price);
        }else{
            throw new RuntimeException("账户:"+username+"-->余额不足.");
        }
    }
}
